package com.smedi.ismedi.authority.starter.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import static com.smedi.ismedi.authority.starter.common.Constant.DEFAULT_STRING;

/**
 * json转换工具
 *
 * @author jiangqinxun
 * @date 2022/8/13 23:28
 */
@Component
@AllArgsConstructor
@Slf4j
public class JsonHelper {
    private final ObjectMapper objectMapper;

    public String objectToJson(Object object) {
        String json = null;
        if (null == object) {
            return DEFAULT_STRING;
        }
        try {
            json = objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException jsonProcessingException) {
            log.error("objectToJson 转换异常");
        }
        return json;
    }

    public <T> T jsonToObject(String json, Class<T> valueType) {
        T t = null;
        try {
            t = objectMapper.readValue(json, valueType);
        } catch (JsonProcessingException jsonProcessingException) {
            log.error("jsonToObject 转换异常");
        }
        return t;
    }
}


